"""
本文件用于将使用new_frame/runner.py 跑推理好的结果文件移动到目标路径下
"""

from glob import glob
import os
import shutil


def move_predictions_from_list(src_path, dst_dir, dry_run=False):
    """
    将单个原始文件拷贝到目标目录。
    Args:
        src_path (str): 原文件完整路径
        dst_dir (str):  目标目录
        dry_run (bool): 是否仅打印而不实际移动
    """
    src_path = os.path.abspath(os.path.expanduser(src_path))
    if not os.path.isfile(src_path):
        raise FileNotFoundError("源文件不存在: {}".format(src_path))

    dst_dir = os.path.abspath(os.path.expanduser(dst_dir))
    if not dry_run:
        os.makedirs(dst_dir, exist_ok=True)

    # 目标文件名
    basename = os.path.basename(src_path)
    dst_file = os.path.join(dst_dir, basename)

    if dry_run:
        print("[DRY-RUN] {} -> {}".format(src_path, dst_file))
        return

    shutil.copy(src_path, dst_file)
    print("[MOVED] {} -> {}".format(src_path, dst_file))


if __name__ == "__main__":
    source_dir_prefix_path = "/media/userdisk5/gqyang/new_frame/model/T2map_"
    dst_dir_prefix = "/media/userdisk5/gqyang/final_result_t2map_test/prediction"
    # tasks = ["cubic_fix_ds_6x4", "cubic_fix_ds_6x5", "cubic_random_ds"]
    tasks = ["cubic_CHEN-REN-GENG_tra_fix_ds_6x4"]
    for task in tasks:
        print(
            f"=========================Processing task: {task}==========================="
        )
        source_file_names = glob(
            os.path.join(source_dir_prefix_path, task, "**", "*.nii.gz"), recursive=True
        )
        print(f"Find total files: {len(source_file_names)}.")  # 4
        for file in source_file_names:
            subject_id = task.split("_")[1]+ '_' + task.split("_")[2]
            subdir_type = task.replace(subject_id, "")
            print(subdir_type)
            final_dst_dir = os.path.join(
                dst_dir_prefix, subject_id, "proposed", subdir_type
            )
            move_predictions_from_list(file, dst_dir=final_dst_dir, dry_run=False)
